package cn.edu.jxau.test;

/**
 * 环的大小（由多少个结点构成）
 * 
 * @author Fudashi
 */
public class Main {

	public static void main(String[] args) {

		Node node1 = new Node(1);
		Node node2 = new Node(2);
		Node node3 = new Node(3);
		Node node4 = new Node(4);
		Node node5 = new Node(5);
		Node node6 = new Node(6);
		node1.next = node2;
		node2.next = node3;
		node3.next = node4;
		node4.next = node5;
		node5.next = node6;
		node6.next = node3;
		System.out.println(circleSize(node1));
	}

	public static int circleSize(Node first) {

		Node slow = first;
		Node fast = first;
		int size = -1;
		while (fast != null && fast.next != null) {
			fast = fast.next.next;
			slow = slow.next;
			if (fast == slow) {
				Node n = fast.next;
				size = 1;
				while (n != fast) {
					n = n.next;
					size++;
				}
				break;
			}
		}
		return size;
	}
}

class Node {

	public int data;
	public Node next;

	public Node(int data) {
		this.data = data;
	}
}